import 'package:automated_test/common/constant.dart';
import 'package:automated_test/common/db_helper.dart';
import 'package:automated_test/common/myLog.dart';
import 'package:automated_test/common/network.dart';
import 'package:automated_test/l10n/DemoLocalizations.dart';
import 'package:automated_test/model/device_info.dart';
import 'package:automated_test/routers/home/search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:permission_handler/permission_handler.dart';

///主页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  ///Appbar
  AppBar buildAppBar(context) => AppBar(
        toolbarHeight: Dimension.h56,
        title: Text(
          DemoLocalizations.of(context).home,
          style: TextStyle(fontSize: Dimension.sp20, color: Colors.black),
        ),
        leading: IconButton(
          padding: EdgeInsets.all(Dimension.sp8),
          icon: Icon(
            Icons.arrow_back,
            size: Dimension.sp24,
            color: Colors.black,
          ),
          onPressed: () => Navigator.pop(context),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        actions: [
          _buildSearchButton(context),
          _buildAddButton(context),
        ],
        elevation: 1,
      );

  ///构建搜索按钮
  Widget _buildSearchButton(context) => IconButton(
        onPressed: () {
          showSearch(context: context, delegate: SearchBarDelegate());
        },
        icon: Icon(
          Icons.search,
          size: Dimension.sp24,
          color: Colors.black,
          semanticLabel: DemoLocalizations.of(context).search,
          textDirection: TextDirection.ltr,
        ),
      );

  ///Appbar 右上角添加按钮
  Widget _buildAddButton(context) => PopupMenuButton(
        icon: Icon(
          Icons.add_circle_outline,
          size: Dimension.sp24,
          color: Colors.black,
        ),
        offset: Offset(0, Dimension.h60),
        itemBuilder: (context) {
          return [
            PopupMenuItem(
              value: 1,
              child: ListTile(
                leading: Icon(
                  Icons.qr_code,
                  size: Dimension.sp20,
                ),
                title: Text(
                  DemoLocalizations.of(context).scan,
                  style: TextStyle(fontSize: Dimension.sp15),
                ),
                trailing: null,
              ),
            ),
          ];
        },
        onSelected: (value) async {
          if (value == 1) {
            if (await Permission.camera.request().isGranted) {
              Navigator.pushNamed(context, "/QRScan");
            } else {
              MyLog.e("扫一扫", "相机未授权");
              EasyLoading.showError(
                  DemoLocalizations.of(context).cameraNotAuthorized,
                  dismissOnTap: true);
            }
          }
        },
      );

  @override
  initState() {
    super.initState();

    ///设置系统底部导航栏为白色
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        systemNavigationBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark));

    ///设置系统显示顶部通知栏和底部导航栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: SafeArea(
        child: HomeContent(),
      ),
      backgroundColor: Colors.white,
    );
  }
}

class HomeContent extends StatefulWidget {
  @override
  _HomeContentState createState() => _HomeContentState();
}

class _HomeContentState extends State<HomeContent> {
  ///从数据库查询到的闸机mac列表
  List<String>? gates;

  ///构建显示主板状态的视图
  Widget _buildListItem(BuildContext context, int index) => Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(Dimension.r20)),
        child: FutureBuilder(
          future: gates == null ? null : Network.getDeviceInfo(gates![index]),
          builder: (context, snap) {
            if (snap.connectionState == ConnectionState.done && snap.hasData) {
              var result = snap.data as Map;
              var deviceInfo = DeviceInfo.fromJson(result);
              var code = result["code"];
              var msg = result["message"];
              var data = result["data"];
              var status;
              var loginAt;
              if (deviceInfo.data != null) {
                status = deviceInfo.data?.rows?[0].isDeviceOnline;
                loginAt = deviceInfo.data?.rows?[0].loginAt;
              }

              return ListTile(
                leading: status == 1
                    ? Icon(
                        Icons.wifi_outlined,
                        color: Colors.green,
                        size: Dimension.sp24,
                      )
                    : Icon(
                        Icons.wifi_off,
                        size: Dimension.sp24,
                      ),
                title: Text(
                  gates![index],
                  style: TextStyle(fontSize: Dimension.sp20),
                ),
                subtitle: loginAt == null
                    ? null
                    : Text(
                        "${DemoLocalizations.of(context).loginTime}：${DateTime.fromMillisecondsSinceEpoch(loginAt).toString()}",
                        style: TextStyle(fontSize: Dimension.sp16),
                      ),
                trailing: Text(
                  status == 1
                      ? DemoLocalizations.of(context).online
                      : DemoLocalizations.of(context).offline,
                  style: TextStyle(
                      fontSize: Dimension.sp20,
                      color: status == 1 ? Colors.green : Colors.red),
                ),
                onTap: () {
                  Navigator.pushNamed(context, "/GateTest",
                      arguments: {"value": gates![index]});
                },
                onLongPress: () async {
                  showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: Text(
                        "确认删除吗？",
                        style: TextStyle(fontSize: Dimension.sp20),
                      ),
                      actions: [
                        TextButton(
                            onPressed: () async {
                              await DbHelper.deleteGate(gates![index]);
                              await getGates();
                              Navigator.of(context).pop();
                            },
                            child: Text(
                              "确定",
                              style: TextStyle(fontSize: Dimension.sp18),
                            )),
                        TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text(
                            "取消",
                            style: TextStyle(fontSize: Dimension.sp18),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              );
            }
            return CupertinoActivityIndicator();
          },
        ),
      );

  ///查询数据库中所有闸机Mac，并更新视图
  Future getGates() =>
      DbHelper.queryGates().then((value) => setState(() => gates = value));

  @override
  initState() {
    super.initState();
    getGates();
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///构建listview 显示主板状态
  Widget _buildGateList() => RefreshIndicator(
        child: ListView.builder(
          padding: EdgeInsets.all(Dimension.sp20),
          itemCount: gates == null ? 0 : gates?.length,
          itemBuilder: _buildListItem,
        ),
        onRefresh: getGates,
      );

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height -
          kToolbarHeight -
          kBottomNavigationBarHeight -
          MediaQuery.of(context).padding.top,
      child: gates == null ? _buildRefreshIndicator(context) : _buildGateList(),
    );
  }

  ///构建数据库没有闸机Mac时显示的布局
  RefreshIndicator _buildRefreshIndicator(BuildContext context) {
    return RefreshIndicator(
      child: ListView(
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            child: Center(
              child: Text(
                DemoLocalizations.of(context).empty,
                style: TextStyle(fontSize: Dimension.sp25),
              ),
            ),
          ),
        ],
      ),
      onRefresh: getGates,
    );
  }
}
